import 'dart:async';
import 'dart:io';

import 'package:flutter/material.dart';
import 'package:flutter_app/tools/http.dart';
import 'package:flutter_app/view/dialog/toast.dart';
import 'package:flutter_app/common/global.dart';
import 'package:flutter_app/style/color.dart';
import 'package:flutter_app/view/dialog/user_info_dialog.dart';
import 'package:flutter_app/model/tweet.dart';
import 'package:wechat_assets_picker/wechat_assets_picker.dart';
import 'package:flutter_app/model/image.dart' as modeImage;

class TweetAddView extends StatefulWidget {
  @override
  _TweetAddViewState createState() => _TweetAddViewState();
}

class _TweetAddViewState extends State<TweetAddView> {
  Tweet tweet = Tweet();
  List<Widget> imageList = []; //图片显示列表，显示已选择的图片
  List<AssetEntity> assets = List<AssetEntity>(); //已选择的图片资源
  List<String> imagePathList = []; //已选择的图片文件列表。

  GlobalKey<FormState> formKey = GlobalKey<FormState>();

  String userName = "";
  String userEmail = "";

//选择照片
  Future<void> loadAssets() async {
    List<AssetEntity> resultList;
    String error;

    try {
      resultList =
          await AssetPicker.pickAssets(context, selectedAssets: assets);
    } on Exception catch (e) {
      error = e.toString();
      print(error);
    }

    if (resultList != null) {
      assets = List<AssetEntity>.from(resultList);
    }
    imageList = [];
    imagePathList = [];
    for (int i = 0; i < assets.length; i++) {
      AssetEntity asset = assets[i];
      File file = await asset.file;

      imagePathList.add(file.path);
      imageList.add(Image.file(file));
    }
    setState(() {});
  }

  //发布动态
  releaseTweet() async {
    if (tweet.text.length == 0 && imagePathList.length == 0) {
      showDialog(
        context: context,
        builder: (BuildContext context) {
          return AlertDialog(
            title: Text("提示"),
            content: Text("至少说点什么吧。"),
          );
        },
      );
      return;
    }
    bool uploadImageFlag = await uploadImage(tweet);
    if (uploadImageFlag) {
      m_http.issueTweet(tweet).then((value) async {
        if (value == "ok") {
          Toast.toast(context, msg: "发送成功~", showTime: 1000);

          await Future.delayed(Duration(milliseconds: 1000), () {
            Navigator.of(context).pop();
          });
        } else {
          Toast.toast(context, msg: "发送失败~", showTime: 1000);
        }
      });
    } else {
      Toast.toast(context, msg: "发送失败~", showTime: 1000);
    }
  }

  //上传照片
  Future<bool> uploadImage(Tweet tweet) async {
    List<String> iamgeUrlList = [];
    List<String> imageThumbnailUrlList = []; //上传的缩略图列表。

    //显示上传进度
    Toast.toast(context, msg: "正在发布", always: true);

    final lb = await Global.loadBalancer;
    String compressionType = "m";
    if (imagePathList.length > 1) {
      compressionType = "s";
    }
    for (var i = 0; i < imagePathList.length; i++) {
      Map resultMsg = await lb.run<Map, modeImage.Image>(
          m_http.uploadImageFile,
          modeImage.Image(
              filePath: imagePathList[i], compressionType: compressionType));
      if (resultMsg["msg"] == "ok") {
        iamgeUrlList.add(resultMsg["imageName"]);
        imageThumbnailUrlList.add(resultMsg["thumbnailName"]);
        Toast.toast(context,
            msg: "上传图片中~ （${i + 1}/${imagePathList.length}）", always: true);
      } else {
        Toast.toast(context,
            msg: "图片（${i + 1}/${imagePathList.length}）上传失败", showTime: 2000);
        return false;
      }
    }
    tweet.images = iamgeUrlList;
    tweet.thumbnails = imageThumbnailUrlList;
    return true;
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
        resizeToAvoidBottomInset: false,
        appBar: AppBar(
          backgroundColor: m_color.black,
          leading: IconButton(
            padding: EdgeInsets.fromLTRB(0, 0, 10, 0),
            alignment: Alignment.centerRight,
            icon: (Icon(Icons.arrow_back)),
            onPressed: () {
              Navigator.of(context).pop();
            },
          ),
        ),
        //body占屏幕的大部分
        body: Container(
            padding: EdgeInsets.all(20.0),
            child: Column(
              children: [
                Scrollbar(
                  child: Container(
                    decoration: new BoxDecoration(
                        border:
                            new Border.all(color: Color(0xFF000000), width: 1),
                        borderRadius: new BorderRadius.circular((5.0))),
                    height: 350,
                    child: SingleChildScrollView(
                      scrollDirection: Axis.vertical,
                      child: Container(
                        padding: EdgeInsets.fromLTRB(10, 0, 10, 5),
                        child: TextFormField(
                          key: formKey,
                          decoration: new InputDecoration(
                            border: InputBorder.none,
                            hintText: '内容',
                          ),
                          maxLines: null,
                          minLines: 22,
                          onChanged: (value) {
                            tweet.text = value ?? "";
                          },
                        ),
                      ),
                    ),
                  ),
                ),
                SingleChildScrollView(
                  child: SizedBox(
                    height: 105,
                    child: ListView(
                      children: imageList,
                      scrollDirection: Axis.horizontal,
                    ),
                  ),
                ),
                Expanded(child: SizedBox()),
                Divider(),
                Row(
                  children: [
                    InkWell(
                      child: SizedBox(
                        child: Icon(
                          Icons.photo_camera,
                          color: m_color.grey,
                          size: 28,
                        ),
                      ),
                      onTap: loadAssets,
                    ),
                    Expanded(child: SizedBox()),
                    Container(
                      margin: EdgeInsets.fromLTRB(10, 0, 10, 0),
                      child: InkWell(
                        child: SizedBox(
                          child: Icon(
                            Icons.account_circle,
                            color: m_color.grey,
                            size: 28,
                          ),
                        ),
                        onTap: () {
                          //显示 dialog
                          showDialog(
                            context: context,
                            barrierDismissible: true, //点击dialog外部 是否可以销毁
                            builder: (BuildContext context) {
                              return UserInfoDialog();
                            },
                          ).then((value) => setState(() {}));
                        },
                      ),
                    ),
                    InkWell(
                      child: SizedBox(
                        child: Icon(
                          Icons.send,
                          color: m_color.grey,
                          size: 28,
                        ),
                      ),
                      onTap: releaseTweet,
                    )
                  ],
                )
              ],
            )));
  }
}
